import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

// https://vite.dev/config/
export default defineConfig(({ command, mode }) => {
  // 根据当前工作目录中的 `mode` 加载 .env 文件
  const env = loadEnv(mode, process.cwd());

  return {
    base: "./",
    resolve: {
      alias: {
        "@": resolve(__dirname, "src"), // 设置 @ 指向 src 目录
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          // 全局变量已经在各个文件中通过 @use 引入
        },
      },
    },
    plugins: [
      vue(),
      // ElementPlus 组件和 API 自动导入
      AutoImport({
        resolvers: [ElementPlusResolver()], // 自动导入 ElementPlus 相关的 API  如 ElMessage
        imports: ["vue", "vue-router", "pinia"], // 自动导入 Vue、Vue Router、Pinia 相关 API
      }),
      Components({
        resolvers: [ElementPlusResolver()], //  自动导入 ElementPlus 组件
        dirs: ["src/components"], // 组件所在目录
      }),
      // SVG 图标插件配置
      createSvgIconsPlugin({
        iconDirs: [resolve(__dirname, "src/assets/icons")], // 指定需要缓存的图标文件夹
        symbolId: "icon-[dir]-[name]", // 指定 symbolId 格式
      }),
    ],
    server: {
      host: "0.0.0.0",
      port: 3000,
      open: true,
      hmr: {
        overlay: false,
      },
      proxy:
        env.VITE_USE_PROXY === "true"
          ? {
              "/api": {
                target: env.VITE_PROXY_TARGET,
                changeOrigin: true,
                rewrite: (path) => path.replace(/^\/api/, ""),
              },
            }
          : null,
    },
    build: {
      outDir: "dist",
      assetsDir: "assets",
      // 生产环境移除 console 和 debugger
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      // 分割大文件
      rollupOptions: {
        output: {
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
          manualChunks: {
            vue: ["vue", "vue-router", "pinia"],
            elementPlus: ["element-plus"],
          },
        },
      },
    },
  };
});
